package com.kaibes.im.view.fragment;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.kaibes.im.R;
import com.kaibes.im.model.SocketWorker;
import com.kaibes.im.model.data.UserListviewData;
import com.kaibes.im.model.hanlder.BaseHandler;
import com.kaibes.im.utils.BirthUtil;
import com.kaibes.im.utils.StaticValuesUtil;

public class UserInformationEditFragment extends KaibesFragment implements
	OnClickListener {

    private ArrayList<UserListviewData> userListviewDatas;
    private LinearLayout llUserinformation;
    private ArrayList<EditText> editTexts;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	setHandler(new BaseHandler<UserInformationEditFragment>(this) {

	    @Override
	    public void handleMessage(Message msg) {
		switch (msg.what) {
		case 1:
		    for (int i = 0; i < editTexts.size(); i++) {
			if (!editTexts.get(i).getText().toString()
				.equals(userListviewDatas.get(i).getContent())) {
			    editTexts.get(i).setText(
				    userListviewDatas.get(i).getContent());
			}
		    }
		    break;

		default:
		    break;
		}
	    }
	});
	super.onCreate(savedInstanceState);
    }

    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    Bundle savedInstanceState) {
	View rootView = inflater.inflate(R.layout.fragment_userinformation_2,
		container, false);
	editTexts = new ArrayList<EditText>();
	llUserinformation = (LinearLayout) rootView
		.findViewById(R.id.llUserinformation);
	userListviewDatas = UserListviewData
		.getArraylist(getKaibesApplication().getUserInformationData());

	for (int i = 0; i < userListviewDatas.size(); i++) {
	    View view = inflater.inflate(R.layout.list_item_uerinformation,
		    llUserinformation, false);

	    if (i == 0) {
		view.setPadding(0, 50, 0, 50);
	    }

	    if (i == 4 || i == 9 || i == 10) {
		view.setPadding(0, 0, 0, 50);
	    }
	    
	    if (i == userListviewDatas.size()-2||i == userListviewDatas.size()-1) {
		((EditText)view.findViewById(R.id.tvUserinformationContent)).setSingleLine(false);
	    }

	    TextView textView = (TextView) view
		    .findViewById(R.id.tvUserinformationName);
	    EditText editText = (EditText) view
		    .findViewById(R.id.tvUserinformationContent);
	    textView.setText(userListviewDatas.get(i).getName());
	    editText.setText(userListviewDatas.get(i).getContent());

	    llUserinformation.addView(view);
	    editTexts.add(editText);

	}

	String sex = getKaibesApplication().getUserInformationData().getSex();
	if (sex.equals(StaticValuesUtil.MAN)) {
	    ((RadioButton) rootView.findViewById(R.id.rbUserinformationMan))
		    .setChecked(true);
	} else {
	    ((RadioButton) rootView.findViewById(R.id.rbUserinformationWoman))
		    .setChecked(true);
	}

	rootView.findViewById(R.id.tvUserinformationCancel).setOnClickListener(
		this);
	rootView.findViewById(R.id.tvUserinformationComplete)
		.setOnClickListener(this);
	rootView.findViewById(R.id.btUserinformationCancel).setOnClickListener(
		this);

	((RadioGroup) rootView.findViewById(R.id.rgUserinformationSex))
		.setOnCheckedChangeListener(new OnCheckedChangeListener() {
		    @Override
		    public void onCheckedChanged(RadioGroup group, int checkedId) {
			if (checkedId == R.id.rbUserinformationMan) {
			    editTexts.get(1).setText(StaticValuesUtil.MAN);
			} else {
			    editTexts.get(1).setText(StaticValuesUtil.WOMAN);
			}

			getView().findViewById(R.id.llUserinformationSex)
				.setVisibility(View.GONE);
		    }
		});

	editTexts.get(1).setKeyListener(null);
	editTexts.get(2).setKeyListener(null);
	editTexts.get(3).setKeyListener(null);
	editTexts.get(4).setKeyListener(null);

	editTexts.get(1).setClickable(true);
	editTexts.get(2).setClickable(true);
	editTexts.get(3).setClickable(true);
	editTexts.get(4).setClickable(true);

	editTexts.get(1).setOnClickListener(this);
	editTexts.get(2).setOnClickListener(this);
	editTexts.get(3).setOnClickListener(this);
	editTexts.get(4).setOnClickListener(this);

	return rootView;
    }

    @Override
    public boolean onBackPressed() {
	getKaibesActivity().changeFragment(getLastFragmentAndSetNull());
	getView().findViewById(R.id.llUserinformationSex).setVisibility(
		View.GONE);
	return false;
    }

    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.tvUserinformationCancel:
	    onBackPressed();
	    break;

	case R.id.tvUserinformationComplete: {
	    JSONObject jsonObject = new JSONObject();
	    for (int i = 0; i < editTexts.size(); i++) {
		if (!editTexts.get(i).getText().toString()
			.equals(userListviewDatas.get(i).getContent())) {

		    userListviewDatas.get(i).setContent(
			    editTexts.get(i).getText().toString());
		    try {
			jsonObject.put(userListviewDatas.get(i).getKey(),
				userListviewDatas.get(i).getContent());
		    } catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }

		    if (i == 2) {
			i += 2;
		    }
		}
	    }
	    if (jsonObject.length() > 0) {
		getKaibesApplication().sendData(1,
			SocketWorker.ACTION_CHANGE_USERINFO, jsonObject);
	    }
	    getKaibesActivity().changeFragment(getLastFragmentAndSetNull());
	    break;
	}

	case R.id.btUserinformationCancel:
	    getView().findViewById(R.id.llUserinformationSex).setVisibility(
		    View.GONE);
	    break;

	default: {
	    // 性别选择器
	    if (v == editTexts.get(1)) {
		getView().findViewById(R.id.llUserinformationSex)
			.setVisibility(View.VISIBLE);
	    }

	    // 日期选择器
	    if (v == editTexts.get(2) || v == editTexts.get(3)
		    || v == editTexts.get(4)) {
		String birth = editTexts.get(2).getText().toString().trim();
		Date date = null;
		try {
		    date = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
			    .parse(birth);
		} catch (ParseException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		}
		Calendar calendar = Calendar.getInstance(Locale.CHINA);
		calendar.setTime(date);

		new DatePickerDialog(getKaibesActivity(),
			DatePickerDialog.THEME_HOLO_LIGHT,
			new OnDateSetListener() {

			    @Override
			    public void onDateSet(DatePicker view, int year,
				    int monthOfYear, int dayOfMonth) {

				String birth = String.format(Locale.CHINA,
					"%d-%d-%d", year, monthOfYear + 1,
					dayOfMonth);

				if (!birth.equals(getKaibesApplication()
					.getUserInformationData().getBirth())) {
				    editTexts.get(2).setText(birth);
				    editTexts.get(3).setText(
					    BirthUtil.getAge(birth) + "");
				    editTexts.get(4).setText(
					    BirthUtil.getConstellation(birth));
				}
			    }
			}, calendar.get(Calendar.YEAR),
			calendar.get(Calendar.MONTH),
			calendar.get(Calendar.DAY_OF_MONTH)).show();
	    }
	}
	    break;
	}
    }

    @Override
    protected void reset() {
	refresh(1);
    }

}
